import router from "@/router"
import { postLogin } from "@/api/blog/user"
import {ElMessage} from "element-plus"
import { ElLoading as Loading } from 'element-plus';

const state = {
  userInfo: {},
  userRole:''
}

const getters = {
  userInfo:(state) => state.userInfo.username?state.userInfo:null|| JSON.parse(localStorage.getItem("userInfo")) || null,
  token: (state) => state.userInfo.token || JSON.parse(localStorage.getItem("token")) || null,
  userRole:(state) => state.userRole || localStorage.getItem("userRole")
}

const mutations = {
  set_userInfo(state, payload) {
    const { token } = payload
    if (!token) return

    state.userInfo = payload
    localStorage.setItem("userInfo", JSON.stringify(payload))
    localStorage.setItem("token", JSON.stringify(payload.token))

    router.push('/')
  },

  clear_userInfo(state, payload){
    state.userInfo = {}
    state.userRole = undefined
    localStorage.removeItem("userInfo")
    localStorage.removeItem("token")
    localStorage.removeItem("userRole")
    router.push("/login")
  },

  set_userRole(state,payload) {
    state.userRole = payload
    localStorage.setItem("userRole", payload)
  }
}

const actions = {
  async login({ commit }, payload) {
    const loadingInstance = Loading.service({
      lock: true,
      text: '请耐心等待…',
      background: 'rgba(0, 0, 0, 0.65)',
      customClass:'loginLoading'
    });
    const res = await postLogin(payload)
    const { code,msg, data, } = res
    if (code === 200) {
      setTimeout(() => {
        loadingInstance.close();
        commit("set_userInfo", data)
        commit("set_userRole", 'admin')
      }, 1500);
    }else {
      loadingInstance.close();
      ElMessage.error(msg)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
